package com.bite.f.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.f.domain.exam.Exam;
import com.bite.f.domain.exam.dto.ExamQueryDTO;
import com.bite.f.domain.exam.vo.ExamVO;
import com.bite.f.domain.user.UserExam;
import com.bite.f.manager.ExamCacheManager;
import com.bite.f.mapper.user.UserExamMapper;
import com.bite.f.mapper.exam.ExamMapper;
import com.bite.f.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ExamCacheManager examCacheManager;
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public int enter(String token, Long examId) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);

        Exam exam = examMapper.selectById(examId);
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId,examId)
                .eq(UserExam::getUserId,userId));
        if(userExam != null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId,examId);
         userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        Long total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(examQueryDTO.getType(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamVOList(examVOList);
        return TableDataInfo.success(examVOList, total);
    }
    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //查找用户是否参加管相应比赛
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        for(ExamVO examVO : examVOList) {
            if(userExamIdList.contains(examVO.getExamId())){
                examVO.setEnter(true);
            }
        }
        return;
    }
}















































